﻿using MailKit.Net.Smtp;
using MimeKit;
using MimeKit.Text;
using WidgetsDesign.API.Models;

namespace WidgetsDesign.API.Helper
{
    /// <summary>
    /// 发送邮箱
    /// </summary>
    [Serializable]
    public static class EmailHelper
    {
        public static bool SendEmail(string title, string receiveNmae, string receiveEmail, string code)
        {
            var emailInfo = new Email
            {
                Username = "noreply@iframe.cc",
                Password = "Walker7355608",
                Port = 465,
                SmtpServer = "smtp.exmail.qq.com"
            };
            try
            {
                MimeMessage message = new MimeMessage();
                //发件人
                message.From.Add(new MailboxAddress("Iframe", emailInfo.Username));
                //收件人
                message.To.Add(new MailboxAddress(receiveNmae, receiveEmail));
                //标题
                message.Subject = title;
                TextPart body = new TextPart(TextFormat.Html)
                {
                    Text = $"<h1>您的验证码为:<span style='color:#006cbe'>{code}</span></h1> "
                };

                //创建Multipart添加附件
                Multipart multipart = new Multipart("mixed");
                multipart.Add(body);

                //正文
                message.Body = multipart;

                using (SmtpClient client = new SmtpClient())
                {
                    //Smtp服务器
                    client.Connect(emailInfo.SmtpServer, emailInfo.Port, true);
                    if (client.IsConnected)
                    {
                        //登录
                        client.Authenticate(emailInfo.Username, emailInfo.Password);
                        //发送
                        string result = client.Send(message);
                    }

                    //断开
                    client.Disconnect(true);
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
